package ac.svn.accesscontrol.ui.helper;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.swing.JList;
import javax.swing.SwingUtilities;

import ac.svn.accesscontrol.store.ISVNItem;
import ac.svn.accesscontrol.ui.UIComponentLibrary;
import ac.svn.accesscontrol.ui.model.ThreadedListModel;

public class LocationFilter implements ILister
{
	private String criteria = "";
	private Thread thread ;
	private JList targetList;
	private ThreadedListModel listModel;
	private List<ISVNItem> sourceList;

	public LocationFilter(String componentId,String model)
	{
		targetList = (JList) UIComponentLibrary.getComponent(componentId);
		listModel = (ThreadedListModel) UIComponentLibrary.getComponent(model); 

		thread = new Thread(new Runnable() 
		{
			@Override
			public void run() 
			{
				synchronized (sourceList) 
				{
					listModel.clear();
					for(ISVNItem item: sourceList)
					{
						if(item.getMetaData().toLowerCase().contains(criteria.toLowerCase()))
						{
							listModel.addElement(item);
						}
					}
				}
				SwingUtilities.invokeLater(new Runnable() 
				{
					@Override
					public void run() 
					{
						targetList.clearSelection();
						SwingUtilities.updateComponentTreeUI(targetList);						
					}
				});

			}
		}) ;
	}

	public void filterList(Set<ISVNItem> sourceSet, String criteria) 
	{
		if(null != sourceList)
		{
			synchronized (sourceList) 
			{

				this.sourceList = null;
				this.sourceList = new ArrayList<ISVNItem>(sourceSet);
			}
		}
		else
		{
			this.sourceList = new ArrayList<ISVNItem>(sourceSet);
		}
		this.criteria = criteria;
		if(thread.isAlive())
		{
			thread.interrupt();
		}
		thread.run();

	}

	public void filterList(List<ISVNItem> sourceLst, String criteria) 
	{
		if(null != sourceList)
		{
			synchronized (sourceList) 
			{
				this.sourceList = null;
				this.sourceList = sourceLst;

			}
		}
		else
		{
			this.sourceList = sourceLst;
		}
		this.criteria = criteria;
		if(thread.isAlive())
		{
			thread.interrupt();
		}
		thread.run();

	}

	public String getCriteria() {
		return criteria;
	}

	public void setCriteria(String criteria) {
		this.criteria = criteria;
	}

	public JList getTargetList() {
		return targetList;
	}

	public void setTargetListView(JList targetList) {
		this.targetList = targetList;
	}

	public ThreadedListModel getListModel() {
		return listModel;
	}

	public void setListModel(ThreadedListModel listModel) {
		this.listModel = listModel;
	}

	public List<ISVNItem> getSourceList() {
		return sourceList;
	}

	public void setSourceList(List<ISVNItem> sourceList) {
		this.sourceList = sourceList;
	}

	@Override
	public void listItems(Set<ISVNItem> itemsList) {
		filterList(itemsList, "");
	}

	@Override
	public void refresh() {
		filterList(sourceList, "");

	}


}
